package my.mall.config.auth;

import my.mall.config.auth.Login;
import my.mall.entity.Manager;
import my.mall.common.pojo.LoginUser;
import my.mall.service.ManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import static org.springframework.web.context.request.RequestAttributes.SCOPE_REQUEST;

@Component
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private ManagerService managerService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(LoginUser.class) && parameter.hasParameterAnnotation(Login.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) {
        Object username = request.getAttribute("username", SCOPE_REQUEST);
        Manager manager = managerService.getManagerByName((String) username);
        LoginUser user = new LoginUser();
        user.setUserId(manager.getMgId()).setUsername(manager.getMgName()).setRoleId(manager.getRoleId());
        return user;
    }

}
